package com.didispace.chapter11;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.didispace.chapter11.service.impl.CameraTemperatureAlarmServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

@RestController
@Slf4j
public class HelloController {
    @Autowired
    private CameraTemperatureAlarmServiceImpl cameraTemperatureAlarmService;

    @PostConstruct
    private void init(){
//        startDel(null,null);
        startDel(null,2L,"05");
    }

    /**
     *
     * @param count 启动的线程数，默认 1
     * @param timeInterval 休眠的时间，默认5分钟， 单位：分钟
     * @param minuteFlag 分钟数标记，默认05，（满足此标记的保留数据）
     * @return
     */
    @RequestMapping("/startDel")
    public String startDel(Integer count,Long timeInterval,String minuteFlag) {
        log.info("startDel...");
        if(StrUtil.isBlankIfStr(count)){
            count = 1;
        }
        if(StrUtil.isBlankIfStr(timeInterval)){
            timeInterval =5L;
        }
        Integer finalCount = count;
        long finalTimeInterval = timeInterval;
        IntStream.range(0,count).forEach(i->{
            ThreadUtil.sleep(finalCount, TimeUnit.SECONDS);

            Future<?> future = ThreadUtil.execAsync(() -> {
                while(true){
                    try {

                        log.info("调用删除方法start.{}", i);
                        cameraTemperatureAlarmService.cameraTemperatureAlarmCheck(finalTimeInterval,minuteFlag);
                        log.info("调用删除方法end.{}", i);
                        final long sleepTimes = (finalTimeInterval * 60) + 30;
                        log.info("start休眠:{}秒", sleepTimes);
                        ThreadUtil.sleep(sleepTimes, TimeUnit.SECONDS);//线程执行间隔一定要大于  图片归档的时间，此处多加30秒
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                }
            });
            log.info("future.{}==={}",i, JSON.toJSON(future));
        });

        return "startDel success!!!";
    }

    @RequestMapping("/endDel")
    public String endDel(Integer count) {

        ThreadUtil.interrupt(new Thread(),true);
        return  "endDel success!!!";
    }
}